package com.xky.ui.module.warehouseManagement.select;

import com.xky.pojo.Warehouses;
import lombok.*;

import javax.swing.*;
import java.awt.*;

import java.util.List;

@Setter
public class SelectWarehouse extends JFrame {

    @Getter
    private static Integer Id;
    
    // 存储查询结果
    @Getter
    private static List<Warehouses> searchResults;
    
    // 标记查询是否成功
    @Getter
    private static boolean searchSuccessful = false;
    
    @Getter
    private final WarehouseService warehouseService;
    private JComboBox<String> searchTypeComboBox;
    private JTextField searchTextField;

    public SelectWarehouse(){
        setTitle("查询仓库");
        setSize(400, 220);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        warehouseService = new WarehouseService();
        // 重置搜索状态
        searchSuccessful = false;
        searchResults = null;
        init();
        setVisible(true);
    }

    void init(){
        setLayout(new BorderLayout());

        // 创建主面板，使用GridBagLayout以获得更好的布局控制
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 添加查询类型选择
        JLabel searchTypeLabel = new JLabel("查询类型:");
        searchTypeLabel.setFont(new Font("黑体", Font.BOLD, 16));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        mainPanel.add(searchTypeLabel, gbc);

        // 查询类型下拉框
        searchTypeComboBox = new JComboBox<>(new String[]{"仓库ID", "仓库名称", "仓库编码", "仓库位置", "关键字查询"});
        searchTypeComboBox.setFont(new Font("宋体", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        mainPanel.add(searchTypeComboBox, gbc);

        // 添加标签
        JLabel searchLabel = new JLabel("查询内容:");
        searchLabel.setFont(new Font("黑体", Font.BOLD, 16));
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        mainPanel.add(searchLabel, gbc);

        // 添加文本框
        searchTextField = new JTextField(20);
        searchTextField.setPreferredSize(new Dimension(210, 30));
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        mainPanel.add(searchTextField, gbc);

        // 添加提示信息
        JLabel hintLabel = new JLabel("提示: 关键字查询将搜索名称/编码/位置");
        hintLabel.setFont(new Font("宋体", Font.ITALIC, 12));
        hintLabel.setForeground(Color.GRAY);
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        mainPanel.add(hintLabel, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        // 确定按钮
        JButton searchButton = new JButton("查询");
        searchButton.setFont(new Font("黑体", Font.BOLD, 16));
        searchButton.setBackground(Color.PINK);
        searchButton.setPreferredSize(new Dimension(100, 30));
        buttonPanel.add(searchButton);

        // 取消按钮
        JButton cancelButton = new JButton("取消");
        cancelButton.setFont(new Font("黑体", Font.BOLD, 16));
        cancelButton.setBackground(Color.PINK);
        cancelButton.setPreferredSize(new Dimension(100, 30));
        buttonPanel.add(cancelButton);

        // 添加按钮面板
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        mainPanel.add(buttonPanel, gbc);

        // 确定按钮事件处理
        searchButton.addActionListener(e -> {
            String searchText = searchTextField.getText().trim();
            if (searchText.isEmpty()) {
                JOptionPane.showMessageDialog(SelectWarehouse.this, 
                    "查询内容不能为空", "输入提示", JOptionPane.WARNING_MESSAGE);
                return;
            }
            
            String searchType = (String) searchTypeComboBox.getSelectedItem();
            List<Warehouses> warehouseList = null;
            
            try {
                if ("仓库ID".equals(searchType)) {
                    try {
                        Integer id = Integer.valueOf(searchText);
                        if (id <= 0) {
                            JOptionPane.showMessageDialog(SelectWarehouse.this, 
                                "仓库ID必须为正整数", "输入错误", JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                        warehouseList = WarehouseService.selectWarehousesById(id);
                        Id = id; // 保存ID用于其他操作
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(SelectWarehouse.this, 
                            "请输入有效的数字ID", "输入错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                } else if ("仓库名称".equals(searchType)) {
                    warehouseList = WarehouseService.searchWarehousesByName(searchText);
                } else if ("仓库编码".equals(searchType)) {
                    warehouseList = WarehouseService.searchWarehousesByCode(searchText);
                } else if ("仓库位置".equals(searchType)) {
                    warehouseList = WarehouseService.searchWarehousesByLocation(searchText);
                } else if ("关键字查询".equals(searchType)) {
                    warehouseList = WarehouseService.searchWarehousesByKeyword(searchText);
                }
                
                if (warehouseList != null && !warehouseList.isEmpty()) {
                    // 保存查询结果和成功状态
                    searchResults = warehouseList;
                    searchSuccessful = true;
                    
                    StringBuilder resultMessage = new StringBuilder("查找到 " + warehouseList.size() + " 个匹配仓库：\n");
                    
                    for (int i = 0; i < Math.min(warehouseList.size(), 5); i++) {
                        Warehouses warehouse = warehouseList.get(i);
                        resultMessage.append(String.format("ID: %d, 名称: %s, 编码: %s\n", 
                            warehouse.getWarehouseId(), 
                            warehouse.getWarehouseName(),
                            warehouse.getWarehouseCode()));
                    }
                    
                    if (warehouseList.size() > 5) {
                        resultMessage.append("...(共 ").append(warehouseList.size()).append(" 条记录)");
                    }
                    
                    JOptionPane.showMessageDialog(SelectWarehouse.this, 
                        resultMessage.toString(), "查找成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(SelectWarehouse.this, 
                        "未找到匹配的仓库记录", "查找失败", JOptionPane.ERROR_MESSAGE);
                    Id = null;
                    searchSuccessful = false;
                    searchResults = null;
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(SelectWarehouse.this, 
                    "查询过程中发生错误: " + ex.getMessage(), "查询错误", JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
                searchSuccessful = false;
                searchResults = null;
            }
        });

        // 取消按钮事件处理
        cancelButton.addActionListener(e -> {
            Id = null;
            searchSuccessful = false;
            searchResults = null;
            dispose();
        });

        // 设置回车键触发确定按钮
        getRootPane().setDefaultButton(searchButton);
        
        add(mainPanel, BorderLayout.CENTER);
    }
    
    /**
     * 重置查询状态
     */
    public static void resetSearchStatus() {
        searchSuccessful = false;
        searchResults = null;
        Id = null;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SelectWarehouse::new);
    }

}